package com.easytouch.core.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import com.easytouch.core.Configure;
import com.easytouch.core.MonitorThread;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;

/**
 * 文件相关操作工具类
 * Created by gulin on 2017/7/26.
 */

public class FileTools {

    private static Log mLogger = new Log("FileTools.txt");


    //设置售货机编号到文件中
    public static String setMac2File(final String mac) {
        String result = "00000000";
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            File file = new File(SDCardTools.getSDCardPath() + "/mac.txt");
            if (file.exists()) {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                result = br.readLine();
                if (mac.equals(result)) {
                    return result;
                } else {
                    if ("00000000".equals(result)) {
                        result = mac;
                    } else {
                        if (!mac.equals("00000000")) {
                            result = mac;
                        }
                    }
                }
            } else {
                file.createNewFile();
                result = mac;
            }
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            bw.write(result);
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    //从文件中获取售货机编号
    public static String getMacFromFile() {
        String result = null;
        BufferedReader br = null;
        try {
            File file = new File(SDCardTools.getSDCardPath() + "/mac.txt");
            if (file.exists()) {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                result = br.readLine();
                if (result != null && result.length() == 8 && !result.equals("00000000")) {
                    return result;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 拷贝文件
     *
     * @param fileSrc 原文件
     * @param fileDes 目标文件
     * @return 是否成功
     */
    public static boolean copyFile(final String fileSrc, final String fileDes) {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(fileSrc));
            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(fileDes));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } catch (IOException e) {
            return false;
        } finally {
            try {
                // 关闭流
                if (inBuff != null)
                    inBuff.close();
                if (outBuff != null)
                    outBuff.close();
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }

    public static String getSDCardPath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
        //return "/mnt/sdcard";
    }

    public static String getGameRate(String gameRateInfo) {

        if (!TextUtils.isEmpty(gameRateInfo)) {
            String[] gameInfo = gameRateInfo.split("\\|");
            String gameGoodsFirst = gameInfo[0];
            String[] rate = gameGoodsFirst.split(":");
            String rates = rate[2];
            return rates;
        }
        return "0";
    }

    //读取文件内容
    public static String readFile(final File pFile) {
        String result = null;
        BufferedReader br = null;
        try {
            if (pFile.exists()) {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(pFile)));
                result = br.readLine();
                if (result != null) {
                    return result;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            //logger.e("readFile:" + e.toString());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    //写入内容到文件中
    public static boolean writeFile(final File pFile, final String pContent) {
        BufferedWriter bw = null;
        try {
            if (!pFile.exists()) {
                pFile.createNewFile();
            }
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(pFile)));
            bw.write(pContent);
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
            //logger.e("writeFile:" + e.toString());
            return false;
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 获取游戏总中奖率
     *
     * @param filename
     * @return
     */
    public static String getGameRates(String filename) {
        String result = null;
        BufferedReader br = null;
        try {
            File file = new File(getSDCardPath() + "/" + filename);
            if (file.exists()) {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                result = br.readLine();
                if (result != null) {
                    return result;
                } else {
                    return null;
                }
            } else {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 从assets目录中复制整个文件夹内容
     *
     * @param context Context
     * @param oldPath String  原文件路径  如：/aa
     * @param newPath String  复制后路径  如：xx:/bb/cc
     */
    public static void copyFilesFassets(Context context, String oldPath, String newPath) {
        try {
            InputStream is = context.getAssets().open(oldPath);
            FileOutputStream fos = new FileOutputStream(new File(newPath));
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {//循环从输入流读取 buffer字节
                fos.write(buffer, 0, byteCount);//将读取的输入流写入到输出流
            }
            fos.flush();//刷新缓冲区
            is.close();
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //logger.i("copyFilesFassets:" + e.getCause());
        }
    }

    /**
     * 存储货柜货道容量json数据
     */
    public static void saveMaxStockConfig(int pBox, int pColumn, int pMaxStock) {
        try {
            String mBoxColumn = String.valueOf(pBox) + String.valueOf(pColumn);
            mLogger.i("mBoxColumn:" + mBoxColumn + ",pMaxStock:" + pMaxStock);
            File file = new File(Configure.path + "/data" + "/" + "maxstockconfig.json");
            if (!file.exists())//判断文件是否存在，若不存在则新建
            {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);//实例化FileOutputStream
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");//将字符流转换为字节流
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);//创建字符缓冲输出流对象

            //Map
            HashMap map = new HashMap();
            map.put(mBoxColumn, pMaxStock);
            String gsonDatas = /*GsonUtils.getGsonDatas(map)*/"";
            mLogger.i("gsonDatas:" + gsonDatas);
            bufferedWriter.write(gsonDatas);//将格式化的jsonarray字符串写入文件
            bufferedWriter.flush();//清空缓冲区，强制输出数据
            bufferedWriter.close();//关闭输出流
            //上传监控后台 TODO
            if (Configure.isMonitorOpen) {
                String pData = Tools.addRightSpace((Tools.addLeftSpace(Tools.addLeftZero(String.valueOf(pMaxStock), 2), (pColumn - 1) * 2)), 96);
                mLogger.i("isMonitorOpen85 pData:" + pData);
                MonitorThread.getInstance().addMessage85(pBox, pData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 存储货柜货道容量json数据
     */
    public static void saveServiceMaxStockConfig(String data) {
        String box;
        String column;
        String stock;
        //Map
        HashMap map = new HashMap();
        try {
            String[] split = data.split(",");
            for (int i = 0; i < split.length; i++) {
                box = split[i].substring(0, 2);
                column = split[i].substring(2, 4);
                stock = split[i].substring(4);
                map.put(box + column, stock);
            }
            String serviceMaxStockConfig = getServiceMaxStockConfig();
            File file = new File(Configure.path + "/data" + "/" + "boxColumnStock.txt");

            if(file.exists()){
                file.delete();
            }
            if (!file.exists())//判断文件是否存在，若不存在则新建
            {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);//实例化FileOutputStream
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");//将字符流转换为字节流
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);//创建字符缓冲输出流对象
            String gsonDatas = /*GsonUtils.getGsonDatas(map)*/"";
            mLogger.i("map boxcolumnstock:" + gsonDatas);


            mLogger.i("serviceMaxStockConfig:" + serviceMaxStockConfig);
            if (!TextUtils.isEmpty(serviceMaxStockConfig) && serviceMaxStockConfig != null) {
                String newJSON=serviceMaxStockConfig.substring(0,serviceMaxStockConfig.length()-1)+","+gsonDatas.substring(1,gsonDatas.length());
                mLogger.i("oldJSON:" + serviceMaxStockConfig.substring(0,serviceMaxStockConfig.length()-1));
                mLogger.i("newJSON:" + gsonDatas.substring(1,gsonDatas.length()));
                mLogger.i("newJSON:" + newJSON);
                bufferedWriter.write(newJSON);//将格式化的jsonarray字符串写入文件
                bufferedWriter.flush();//清空缓冲区，强制输出数据
                bufferedWriter.close();//关闭输出流
            }else{
                bufferedWriter.write(gsonDatas);//将格式化的jsonarray字符串写入文件
                bufferedWriter.flush();//清空缓冲区，强制输出数据
                bufferedWriter.close();//关闭输出流
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveBoxColumnStock(String data) {
        try {
            File file = new File(Configure.path + "/data" + "/" + "boxColumnStock.txt");
            if (!file.exists())//判断文件是否存在，若不存在则新建
            {
                mLogger.i("data:" + data);
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);//实例化FileOutputStream
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");//将字符流转换为字节流
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);//创建字符缓冲输出流对象

            //Map
            bufferedWriter.write(data);//将格式化的jsonarray字符串写入文件
            bufferedWriter.flush();//清空缓冲区，强制输出数据
            bufferedWriter.close();//关闭输出流

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取之前存储好的货道容量信息
    public static String getServiceMaxStockConfig() {
        String result = null;
        BufferedReader br = null;
        try {
            File file = new File(Configure.path + "/data" + "/" + "boxColumnStock.txt");
            if (file.exists()) {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                result = br.readLine();
                if (result != null) {
                    return result;
                } else {
                    return null;
                }
            } else {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String getBoxColumnStock() {
        String result = null;
        BufferedReader bufferedReader = null;
        try {
            File file = new File(Configure.path + "/data" + "/" + "boxColumnStock.txt");
            if (!file.exists())//判断文件是否存在，若不存在则新建
            {
                return null;
            } else {
                FileInputStream fileInputStream = new FileInputStream(file);//实例化FileOutputStream
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");//将字符流转换为字节流
                //创建字符缓冲输出流对象
                bufferedReader = new BufferedReader(inputStreamReader);
                result = bufferedReader.readLine();
                if (result != null) {
                    return result;
                } else {
                    return null;
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
